package moo.stargalaxy_datasyncs;

import moo.stargalaxy_bukkit.utils.CommandUtil;
import moo.stargalaxy_datasyncs.api.DataSyncsAPI;
import moo.stargalaxy_datasyncs.config.SyncsConfig;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.*;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.lang.String;

public final class StarGalaxy_DataSyncs extends JavaPlugin implements Listener, CommandExecutor {

    private static Plugin plugin;

    @Override
    public void onEnable() {
        // Plugin startup logic
        plugin = this;
        getServer().getPluginManager().registerEvents(this, this);
        getServer().getPluginCommand("sdatas").setExecutor(this);
        // this.getLogger().info("§f┃ ");
        StarGalaxy_DataSyncs.getPlugin().getServer().getConsoleSender().sendMessage("§f┃ ");
        StarGalaxy_DataSyncs.getPlugin().getServer().getConsoleSender().sendMessage("§f┃  §6§lStarGalaxy-DataSync §e(群星插件-数据同步拓展) ");
        StarGalaxy_DataSyncs.getPlugin().getServer().getConsoleSender().sendMessage("§f┃  §8Version §71.0.0");
        StarGalaxy_DataSyncs.getPlugin().getServer().getConsoleSender().sendMessage("§f┃ ");
        StarGalaxy_DataSyncs.getPlugin().getServer().getConsoleSender().sendMessage("§f┃  §8作者：§a沐老师 §8+ §a寻海");
        StarGalaxy_DataSyncs.getPlugin().getServer().getConsoleSender().sendMessage("§f┃  §8来源：§b星域互联信息 §8(§7http://tb.starmc.cn§8)");
        StarGalaxy_DataSyncs.getPlugin().getServer().getConsoleSender().sendMessage("§f┃ ");
        // 初始化配置
        SyncsConfig.loadYaml(false);
    }

    @Override
    public void onDisable() {
        // Plugin shutdown logic
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if(command.getName().equals("sdatas")){
            if(args.length  == 0 && sender.isOp()){
                sender.sendMessage("§f┃ ");
                sender.sendMessage("§f┃  §6StarGalaxy §c(群星插件帮助-数据同步拓展) ");
                sender.sendMessage("§f┃  §8Version §71.0.0");
                sender.sendMessage("§f┃ ");
                sender.sendMessage("§f┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
                sender.sendMessage("§f┃ ");
                sender.sendMessage("§f┃  §8● §7重载插件配置:");
                sender.sendMessage("§f┃  §8┗━  §a/sdatas reload");
                sender.sendMessage("§f┃  §8● §7手动保存玩家数据:");
                sender.sendMessage("§f┃  §8┗━  §a/sdatas save §e<玩家名称>");
                sender.sendMessage("§f┃  §8● §7手动加载玩家数据:");
                sender.sendMessage("§f┃  §8┗━  §a/sdatas load §e<玩家名称>");
                sender.sendMessage("§f┃  §8● §7向玩家发送文本消息:");
                sender.sendMessage("§f┃  §8┗━  §a/sdatas sendtext §e<玩家名称> <消息内容>");
                sender.sendMessage("§f┃ ");
                return true;
            }
            // 重载配置文件
            if(args.length == 1 && args[0].equals("reload") && (sender.isOp() || sender.hasPermission("sdatas.admin"))){
                SyncsConfig.loadYaml(true);
                sender.sendMessage("§7━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
                sender.sendMessage("§e已重载配置 §8(群星插件帮助-数据同步拓展)");
                return true;
            }
            if(args.length == 2){
                // 手动保存玩家数据到控制台
                if(args[0].equals("save") && Bukkit.getPlayer(args[1]) != null && (sender.isOp() || sender.hasPermission("sdatas.admin"))){
                    DataSyncsAPI.gitAllData(Bukkit.getPlayer(args[1]));
                    sender.sendMessage("§7玩家: " + args[1] +  "§7 操作(保存): §c实时游戏数据 §8→ §6云端数据");
                    return true;
                }
                // 从控制台读取玩家数据同步到游戏
                if(args[0].equals("load") && Bukkit.getPlayer(args[1]) != null && (sender.isOp() || sender.hasPermission("sdatas.admin"))){
                    DataSyncsAPI.syncDownAllData(Bukkit.getPlayer(args[1]));
                    sender.sendMessage("§7玩家: " + args[1] +  "§7 操作(读取): §6云端数据 §8→ §c实时游戏数据");
                    return true;
                }
            }
            if(args.length >= 3){
                // 发送文本消息功能
                if(args[0].equals("sendtext") && Bukkit.getPlayer(args[1]) != null && (sender.isOp() || sender.hasPermission("sdatas.admin"))){
                    // 判断是否后方文本包含空格内容,组合成一体消息
                    if(args.length > 3){
                        StringBuilder message = new StringBuilder();
                        for (int i = 0; i < args.length; i++) {
                            if(i >= 2){
                                message.append(" ").append(args[i]);
                            }
                        }
                        Bukkit.getPlayer(args[1]).sendMessage(message.toString().trim());
                    } else {
                        Bukkit.getPlayer(args[1]).sendMessage(args[2]);
                    }
                    return true;
                }
            }
        }
        return true;
    }

    @EventHandler
    public void chat(AsyncPlayerChatEvent event){
        if(SyncsConfig.getPrevent_LockTime_Sync().containsKey(event.getPlayer().getUniqueId())){
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void chat(PlayerMoveEvent event){
        if(SyncsConfig.getPrevent_LockTime_Sync().containsKey(event.getPlayer().getUniqueId())){
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void chat(PlayerInteractEvent event){
        if(SyncsConfig.getPrevent_LockTime_Sync().containsKey(event.getPlayer().getUniqueId())){
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void chat(InventoryOpenEvent event){
        if(event.getInventory().getType().equals(InventoryType.CRAFTING) && SyncsConfig.getPrevent_LockTime_Sync().containsKey(event.getPlayer().getUniqueId())){
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void join(PlayerJoinEvent event){
        if(event.getPlayer().hasPermission("sdatas.stopautosync") && !event.getPlayer().isOp()){
            return;
        }
        new BukkitRunnable() {
            @Override
            public void run() {
                for (String s : SyncsConfig.getYaml().getStringList("Command_Set.DataSync_Ready")) {
                    CommandUtil.executeCommand(event.getPlayer(), s);
                }
            }
        }.runTask(StarGalaxy_DataSyncs.getPlugin());
        if(SyncsConfig.Enable_SyncLock_Play) SyncsConfig.getPrevent_LockTime_Sync().put(event.getPlayer().getUniqueId(), true);
        new BukkitRunnable() {
            @Override
            public void run() {
                // sync
                DataSyncsAPI.syncDownAllData(event.getPlayer());
                SyncsConfig.getPrevent_LockTime_Sync().remove(event.getPlayer().getUniqueId());
            }
        }.runTaskLater(plugin, SyncsConfig.yaml.getInt("Server_Set.Sync_delay") * 20L);
        Player player = event.getPlayer();
        new BukkitRunnable() {
            @Override
            public void run() {
                if(!player.isOnline()) return;
                // sync
                SyncsConfig.getCanGitData().put(player.getUniqueId(), true);
            }
        }.runTaskLaterAsynchronously(plugin, SyncsConfig.yaml.getInt("Server_Set.Prevent_LockTime_Sync") * 20L);
    }

    @EventHandler
    public void quit(PlayerQuitEvent event){
        if(event.getPlayer().hasPermission("sdatas.stopautosync") && !event.getPlayer().isOp()){
            return;
        }
        Player player = event.getPlayer();
        if(SyncsConfig.getCanGitData().containsKey(player.getUniqueId())){
            DataSyncsAPI.gitAllData(player);
            SyncsConfig.getCanGitData().remove(player.getUniqueId());
        }
    }

    public static Plugin getPlugin() {
        return plugin;
    }

    public static void setPlugin(Plugin plugin) {
        StarGalaxy_DataSyncs.plugin = plugin;
    }
}
